package com.kb.erp.controller;

import com.kb.erp.common.ApiResponse;
import com.kb.erp.domain.other.CrmWaitInvoiceData;
import com.kb.erp.domain.other.InvoiceSearchDTO;
import com.kb.erp.entity.crm.CrmDocumentEntity;
import com.kb.erp.entity.crm.Invoice;
import com.kb.erp.service.K3Service;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

/**
 * crm to k3 invoicing interface
 */
@RestController
@RequestMapping("k3")
public class K3Controller {

    @Resource
    private K3Service k3Service;

    /**
     * 从局域网路径复制文件到本地
     *
     * @param networkPath 根据id获取文件  : d972e7ad-8b22-4875-b66c-76fba3291476
     * @param
     */
//    @GetMapping("/getFileFromLAN")
//    public ResponseEntity<byte[]> getFileFromLAN(String networkPath) throws IOException {
//        try {
//            CrmDocumentEntity crmDocumentEntity = k3Service.queryDocument(networkPath);
//            if (crmDocumentEntity != null) {
//                // url 转换
//                String yearPath = crmDocumentEntity.getYearPath();
//                String monthPath = crmDocumentEntity.getMonthPath();
//                String dayPath = crmDocumentEntity.getDayPath();
//                networkPath = "\\\\192.168.10.12\\attach\\crm\\files\\Invoice\\" + yearPath + "\\" + monthPath + "\\" + dayPath + "\\" + crmDocumentEntity.getAttachId() + "";
//
//                Path path = Paths.get(networkPath);
//                byte[] fileBytes = Files.readAllBytes(path);
//                // 构建响应头
//                HttpHeaders headers = new HttpHeaders();
//                headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
//                headers.setContentDispositionFormData("attachment", crmDocumentEntity.getAttachId());
//                return ResponseEntity.ok()
//                        .headers(headers)
//                        .body(fileBytes);
//            }
//
//        } catch (IOException e) {
//            System.err.println("读取文件失败: " + e.getMessage());
//            throw new RuntimeException("文件读取失败", e);
//        }
//        return null;
//    }

    @GetMapping("/getFileFromLAN")
    public ResponseEntity<byte[]> getFileFromLAN(String networkPath) throws IOException {
        FTPClient ftpClient = new FTPClient();
        try {
            CrmDocumentEntity crmDocumentEntity = k3Service.queryDocument(networkPath);
            if (crmDocumentEntity != null) {
                // FTP连接配置
                ftpClient.connect("192.168.10.12");
                ftpClient.login("k3233", "7Krw6B7D");
                ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
                ftpClient.enterLocalPassiveMode();

                // 构建FTP路径
                String yearPath = crmDocumentEntity.getYearPath();
                String monthPath = crmDocumentEntity.getMonthPath();
                String dayPath = crmDocumentEntity.getDayPath();
                String ftpFilePath = "/Invoice/" + yearPath + "/" + monthPath + "/" + dayPath + "/" + crmDocumentEntity.getAttachId();

                // 从FTP读取文件
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                boolean success = ftpClient.retrieveFile(ftpFilePath, outputStream);

                if (success) {
                    byte[] fileBytes = outputStream.toByteArray();
                    // 构建响应头
                    HttpHeaders headers = new HttpHeaders();
                    headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
                    headers.setContentDispositionFormData("attachment", crmDocumentEntity.getAttachId());
                    return ResponseEntity.ok()
                            .headers(headers)
                            .body(fileBytes);
                }
            }
        } catch (IOException e) {
            System.err.println("FTP文件读取失败: " + e.getMessage());
            throw new RuntimeException("文件读取失败", e);
        } finally {
            try {
                if (ftpClient.isConnected()) {
                    ftpClient.logout();
                    ftpClient.disconnect();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 获取待开票列表
     *
     * @param invoiceSearchDTO
     */
    @PostMapping("/queryWaitInvoiceList")
    public ApiResponse<List<CrmWaitInvoiceData>> queryWaitInvoiceList(@RequestBody InvoiceSearchDTO invoiceSearchDTO) {
        return ApiResponse.success(k3Service.queryWaitInvoiceList(invoiceSearchDTO));
    }
    /**
     * 回写开票信息
     *
     * @param invoice
     */
    @PostMapping("/updateInvoiceInfo")
    public ApiResponse<Boolean> updateInvoiceInfo(@RequestBody Invoice invoice) {
        return ApiResponse.success(k3Service.updateInvoiceInfo(invoice));
    }
}
